package com.zyit.service;

import com.zyit.DataObject.T_user;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter("/*")
public class MyFilter implements Filter {

    // 允许通过的 URI 列表
    private List<String> allowedURIs = Arrays.asList("/", "/login","/goods/goodsDetail.jsp", "/skipIndex", "/sendVer", "/register", "/client", "/common", "/files", "/statics","/emailLongin","/client/register","/client/login.jsp","/client/forgotPassword.jsp","/emailLongin","/forgotPassword","/client/updataByemail.jsp","/UpdataPassword","/emailLonginCC");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化方法，可以在此处进行一些初始化操作
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        request.setCharacterEncoding("UTF-8"); // 设置请求的字符编码为UTF-8，以确保正确处理Unicode字符
        HttpSession session = request.getSession();
        Object user = session.getAttribute("userI");
        String requestURI = request.getRequestURI();
        Object type = session.getAttribute("typeI");


        if (user != null || isAllowedURI(requestURI)) {


            filterChain.doFilter(request, response);
        } else {
            // 否则，重定向到错误页面
            response.sendRedirect("/client/login.jsp?errcode=202");
        }
    }

    private boolean isAllowedURI(String requestURI) {
        // 检查请求的URI是否匹配允许的URI列表中的任何一个
        return allowedURIs.stream().anyMatch(uri -> requestURI.equals(uri) || requestURI.startsWith(uri + "/"));
    }

    @Override
    public void destroy() {
        // 销毁方法，可以在此处进行一些清理操作
    }
}
